/*
	* --------------------------------------------------------------------------
	*
  * Copyright 2011 Matthew West T/A Developer City
	*
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
	*
  *   http://www.apache.org/licenses/LICENSE-2.0
	*
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  *
  * --------------------------------------------------------------------------
*/

function setUp() {
	
	currentProcessed = 0;
	totalPageViews = 0;
	
	startTime = minusThirtyDays();
	
	getStats();
	
	var views = chrome.extension.getViews();

	var backgroundView = views[0];
	showGraph(backgroundView.graphArray, backgroundView.graphArrayLegacy, backgroundView.graphKey);
	
};


/*
*	Get the date 30 days ago
*/
function minusThirtyDays() {
	// Calculate the start date
	// 30 Days before the current date
	var milliMonth = 1000*60*60*24*30; // Calculate how many milliseconds are in 30 days
	var d = new Date();
	var current = d.getTime(); // Set d to the current time
	var offsetDate = current - milliMonth; // Calculate the date/time 30 days ago
	d.setTime(offsetDate); // Reset the date object to the offsetTime
	d.setMinutes(0); // Reset the minutes to 0
	d.setHours(0); // Reset the hours to 0
	d.setSeconds(0); // Reset the seconds to 0
	d.setMilliseconds(0); // Reset the milliseconds to 0
	
	thirtyDaysAgo = d.getTime(); // Set the start time variable to d in milliseconds since epoch
	
	return thirtyDaysAgo;
}


/*
*	Analyse the history data and get the statistic totals
*/
function getStats() {
	var lastThirtyDays = [];
	var previousThirtyDays = [];
	
	// Variables for last 30 days
	var uniquePageCount = 0;
	var uniqueWebsites = 0;
	var totalPageViews = 0;
	
	// Variables for previous 30 days - Used for comparison
	var uniquePageCountLegacy = 0;
	var uniqueWebsitesLegacy = 0;
	var totalPageViewsLegacy = 0;
	
	jobNumber = 0;
	
	/*
	* Worker to handle prcoessing data for the last 30 days
	*/
	var worker = new Worker('js/workers/getStats.js');

	worker.addEventListener('message', function(e) {
	  
		// Check to see if this is the first or second job
		if (jobNumber == 1) {
			
			uniquePageCount = e.data.uniquePageCount;
			uniqueWebsites = e.data.uniqueWebsites;
			totalPageViews = e.data.totalPageViews;
			
			// Show the Top Ten sites
			showTopTen(e.data.topTenSites);
			
			// alert("Sending job two");
			
			var thirtyDays = 1000*60*60*24*30;
			
			// Get the history data for the previous 30 day period
			chrome.history.search({
				'text': '',
				'startTime': (startTime - thirtyDays),
				'endTime': (startTime - 1),
				'maxResults': 1000000000
			},
			function(historyItems) {
				jobNumber++;
				previousThirtyDays = historyItems;
				worker.postMessage({'historyItems': previousThirtyDays, 'jobNumber': jobNumber});
			});
			
		} else {
		
			uniquePageCountLegacy = e.data.uniquePageCount;
			uniqueWebsitesLegacy = e.data.uniqueWebsites;
			totalPageViewsLegacy = e.data.totalPageViews;
			
			showStats(uniqueWebsites, 
								uniquePageCount, 
								totalPageViews, 
								uniqueWebsitesLegacy, 
								uniquePageCountLegacy, 
								totalPageViewsLegacy);
		}
	  
	}, false);
	
	worker.addEventListener('error', onError, false);
	
	// Get the history data for the last days
	chrome.history.search({
		'text': '',
		'startTime': startTime,
		'maxResults': 1000000000
	},
	function(historyItems) {
		jobNumber++;
		lastThirtyDays = historyItems;
		worker.postMessage({'historyItems': lastThirtyDays, 'jobNumber': jobNumber });
	});
	
}


/*
*
*/
function showStats(uniqueWebsites, 
									 uniquePageCount, 
									 totalPageViews, 
									 uniqueWebsitesLegacy, 
									 uniquePageCountLegacy, 
									 totalPageViewsLegacy) {

	// Calculate the changes
	var uwDiff = (uniqueWebsites - uniqueWebsitesLegacy);
	var upDiff = (uniquePageCount - uniquePageCountLegacy);
	var totDiff = (totalPageViews - totalPageViewsLegacy);
									 
	$('#stats').append('<span id="statUW" class="bigTextStat">'+uniqueWebsites+'</span> unique websites '+showDiff(uwDiff)+'<br/>');
	$('#stats').append('<span id="statUP" class="bigTextStat">'+uniquePageCount+'</span> different web pages '+showDiff(upDiff)+'<br/>');
	$('#stats').append('<span id="statTPV" class="bigTextStat">'+totalPageViews+'</span> page views '+showDiff(totDiff)+'');
	
	$('#bottomPanel').css('background', 'none');
	
}


/*
*	
*/
function showDiff(value) {
	var sign;
	var color;
	
	if (value >= 0) {
		sign = "+";
		color = "upStat";
	} else {
		sign = "-";
		color = "downStat";
	}
	
	var diffString = '<span class="diff '+color+'">('+sign+value+')</span>';
	
	return diffString;
}


/*
*	Error handler for workers
*/
function onError(e) {
  error = ['ERROR: Line ', e.lineno, ' in ', e.filename, ': ', e.message].join('');
  alert(error);
}


/*
*
*	@param	url		The url that you wish to add to the array
*/
function showTopTen(topTen) {
	
	for (var i = 0; i < topTen.length; i++) {
		var url = topTen[i][0];
		var visits = topTen[i][1];
		var vText = (visits > 1) ? "visits" : "visit";
		
		document.getElementById('topTenSites').innerHTML += "<li><a href='"+url+"'>"+url+" <span class='topTenVisits'><br/>("+visits+" "+vText+")</span></a></li>";
	}
	
	$('#leftPanel').css('background', 'none');
}



/*
*	Show Graphs
*/
function showGraph(graphArray, graphArrayLegacy, graphKey) {
	var options = {
		series: {
		  lines: { show: true },
		  points: { show: true }
		},
		xaxis: {
		  ticks: graphKey,
			tickSize: 1,
		},
		grid: {
		  show: true,
		  hoverable: true,
		  borderColor: '#4A4A4A'
		},
		colors: [ '#08C', '#008600' ]
	};
	
	$.plot($("#historyGraph"), [ graphArray, graphArrayLegacy ], options);
	$('#topPanel').css('background', 'none');

	function showTooltip(x, y, contents) {
		$('<div id="tooltip">' + contents + '</div>').css( {
		                position: 'absolute',
		                display: 'none',
		                top: y + 8,
		                left: x + 8,
		                border: '1px solid #BABABA',
		                padding: '2px',
		                'background-color': '#CCC',
		                opacity: 0.80 }).appendTo("body").fadeIn(200);
	}

	var previousPoint = null;
	$("#historyGraph").bind("plothover", function (event, pos, item) {
		$("#x").text(pos.x.toFixed(2));
		$("#y").text(pos.y.toFixed(2));

		if (item) {
		  if (previousPoint != item.datapoint) {
		      previousPoint = item.datapoint;
		      
		      $("#tooltip").remove();
		      var x = item.datapoint[0].toFixed(0),
		          y = item.datapoint[1].toFixed(0);
		      
		      showTooltip(item.pageX, item.pageY, y+" web pages");
		  }
		}
		else {
		  $("#tooltip").remove();
		  previousPoint = null;            
		}
	});
}


/*
* TODO: Needs to be added back in
*/
function displayAveragePPD() {
	var average = (totalPageViews / totalDaysUse);
	
	$('#stats').append('<span id="statSPD" class="bigTextStat">'+average.toFixed(0)+'</span> pages per day on average');
}


/*
*	Display the total stats
*	This function is being used for debugging will be removed/modified before release
*/
function displayStats() {
	var numUW = parseInt(rootDomains.length);
	var numUP = parseInt(uniquePages.length);
	
	console.log(numUW + " " + numUP);
	
	for (var i = 0; i < 10; i++) {
		var url = rootDomains[i][0];
		var visits = rootDomains[i][1];
		var vText = (visits > 1) ? "visits" : "visit";
		
		document.getElementById('topTenSites').innerHTML += "<li><a href='"+url+"'>"+url+" <span class='topTenVisits'><br/>("+visits+" "+vText+")</span></a></li>";
		$('#leftPanel').css('background', 'none');
	}

	$('#stats').append('<span id="statUW" class="bigTextStat">'+numUW+'</span> unique websites<br/><span id="statUP" class="bigTextStat">'+numUP+'</span> different web pages<br/><span id="statTPV" class="bigTextStat">'+totalPageViews+'</span> page views<br/>');
	
	$('#bottomPanel').css('background', 'none');
	
	goGoGadgetGraph();
}


/*
*	Get the base url from a url string
*
*	@param	url			The full url which you wish to process
*	@retrn	baseURL	The base url that has been extracted from the given url.
*/
function getBaseURL(url) {
  var baseURL = url.substring(0, url.indexOf('/', 14));
	
	return baseURL;
}
